import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

export default function TestApiPage() {
  const [result, setResult] = useState('');
  const [loading, setLoading] = useState(false);
  const [phone, setPhone] = useState('12345678901');
  const [password, setPassword] = useState('123456');
  const navigate = useNavigate();
  const { login } = useAuth();

  // 处理登录成功
  const handleLoginSuccess = (responseData) => {
    if (responseData && responseData.code === 200 || responseData.code === '200') {
      const userData = responseData.data;
      
      // 保存用户信息到localStorage
      localStorage.setItem('user', JSON.stringify(userData));
      
      // 更新认证上下文
      login(userData);
      
      // 提示用户
      setResult(`登录成功！用户名: ${userData.userName}\n即将跳转到首页...`);
      
      // 3秒后跳转到首页
      setTimeout(() => {
        navigate('/');
      }, 3000);
      
      return true;
    }
    return false;
  };

  const testDirectApi = async () => {
    setLoading(true);
    setResult('测试中...');
    
    try {
      // 直接使用fetch请求
      const response = await fetch('/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          loginType: 1,
          phone: phone,
          password: password,
        }),
      });
      
      const status = `状态码: ${response.status} ${response.statusText}`;
      
      try {
        const data = await response.json();
        setResult(`${status}\n\n响应数据:\n${JSON.stringify(data, null, 2)}`);
        
        // 尝试处理登录成功
        handleLoginSuccess(data);
      } catch (e) {
        setResult(`${status}\n\n无法解析响应数据: ${e.message}`);
      }
    } catch (error) {
      setResult(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };
  
  const testDirectApiWithAxios = async () => {
    setLoading(true);
    setResult('使用axios测试中...');
    
    try {
      // 动态导入axios
      const axios = (await import('axios')).default;
      
      // 创建一个新的axios实例
      const axiosInstance = axios.create({
        baseURL: '',
        timeout: 10000,
      });
      
      // 发送请求
      const response = await axiosInstance.post('/user/login', {
        loginType: 1,
        phone: phone,
        password: password,
      });
      
      setResult(`Axios响应:\n${JSON.stringify(response.data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(response.data);
    } catch (error) {
      let errorMessage = `Axios请求失败: ${error.message}`;
      
      if (error.response) {
        errorMessage += `\n状态码: ${error.response.status}`;
        if (error.response.data) {
          errorMessage += `\n响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
        }
      }
      
      setResult(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  const testDirectServerApi = async () => {
    setLoading(true);
    setResult('直接请求服务器中...');
    
    try {
      // 动态导入axios
      const axios = (await import('axios')).default;
      
      // 直接请求服务器
      const response = await axios.post('http://192.168.2.141:8083/api/user/login', {
        loginType: 1,
        phone: phone,
        password: password,
      }, {
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      setResult(`直接请求服务器响应:\n${JSON.stringify(response.data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(response.data);
    } catch (error) {
      let errorMessage = `直接请求服务器失败: ${error.message}`;
      
      if (error.response) {
        errorMessage += `\n状态码: ${error.response.status}`;
        if (error.response.data) {
          errorMessage += `\n响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
        }
      }
      
      setResult(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  const testLocalhost = async () => {
    setLoading(true);
    setResult('测试localhost:8083中...');
    
    try {
      // 动态导入axios
      const axios = (await import('axios')).default;
      
      // 请求localhost
      const response = await axios.post('http://192.168.2.141:8083/user/login', {
        loginType: 1,
        phone: phone,
        password: password,
      }, {
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      setResult(`localhost响应:\n${JSON.stringify(response.data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(response.data);
    } catch (error) {
      let errorMessage = `localhost请求失败: ${error.message}`;
      
      if (error.response) {
        errorMessage += `\n状态码: ${error.response.status}`;
        if (error.response.data) {
          errorMessage += `\n响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
        }
      }
      
      setResult(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  const testWithoutApi = async () => {
    setLoading(true);
    setResult('测试不带api前缀的路径...');
    
    try {
      // 动态导入axios
      const axios = (await import('axios')).default;
      
      // 添加详细的请求信息
      const requestInfo = {
        url: '/user/login',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {
          loginType: 1,
          phone: phone,
          password: password,
        }
      };
      
      console.log('发送请求:', JSON.stringify(requestInfo, null, 2));
      setResult(`发送请求:\n${JSON.stringify(requestInfo, null, 2)}`);
      
      // 请求不带api前缀的路径
      const response = await axios(requestInfo);
      
      setResult(`不带api前缀响应:\n${JSON.stringify(response.data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(response.data);
    } catch (error) {
      let errorMessage = `不带api前缀请求失败: ${error.message}`;
      
      if (error.response) {
        errorMessage += `\n状态码: ${error.response.status}`;
        if (error.response.data) {
          errorMessage += `\n响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
        }
      }
      
      console.error('请求失败:', errorMessage);
      setResult(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  const testWithApi = async () => {
    setLoading(true);
    setResult('测试带api前缀的路径...');
    
    try {
      // 动态导入axios
      const axios = (await import('axios')).default;
      
      // 请求带api前缀的路径
      const response = await axios.post('/api/user/login', {
        loginType: 1,
        phone: phone,
        password: password,
      }, {
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      setResult(`带api前缀响应:\n${JSON.stringify(response.data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(response.data);
    } catch (error) {
      let errorMessage = `带api前缀请求失败: ${error.message}`;
      
      if (error.response) {
        errorMessage += `\n状态码: ${error.response.status}`;
        if (error.response.data) {
          errorMessage += `\n响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
        }
      }
      
      setResult(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  const testWithFetch = async () => {
    setLoading(true);
    setResult('使用fetch测试API...');
    
    try {
      const requestInfo = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          loginType: 1,
          phone: phone,
          password: password,
        })
      };
      
      console.log('发送fetch请求:', '/user/login', requestInfo);
      
      // 使用fetch API
      const response = await fetch('/user/login', requestInfo);
      const data = await response.json();
      
      setResult(`fetch响应 (${response.status}):\n${JSON.stringify(data, null, 2)}`);
      
      // 尝试处理登录成功
      handleLoginSuccess(data);
    } catch (error) {
      console.error('fetch请求失败:', error);
      setResult(`fetch请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h1>API测试页面</h1>
      
      <div style={{ marginBottom: '20px' }}>
        <label htmlFor="phone">手机号:</label>
        <input 
          type="text" 
          id="phone"
          value={phone} 
          onChange={(e) => setPhone(e.target.value)} 
          style={{ marginLeft: '10px', padding: '5px' }}
        />
        
        <label htmlFor="password" style={{ marginLeft: '20px' }}>密码:</label>
        <input 
          type="password" 
          id="password"
          value={password} 
          onChange={(e) => setPassword(e.target.value)} 
          style={{ marginLeft: '10px', padding: '5px' }}
        />
      </div>
      
      <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
        <button 
          onClick={testDirectApi} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          测试代理API (Fetch)
        </button>
        
        <button 
          onClick={testDirectApiWithAxios} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          测试代理API (Axios)
        </button>
        
        <button 
          onClick={testDirectServerApi} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          直接请求服务器
        </button>
      </div>
      
      <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
        <button 
          onClick={testLocalhost} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          测试192.168.2.141:8083
        </button>
        
        <button 
          onClick={testWithoutApi} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          测试不带api前缀
        </button>
        
        <button 
          onClick={testWithApi} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          测试带api前缀
        </button>
      </div>
      
      <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
        <button 
          onClick={testWithFetch} 
          disabled={loading}
          style={{ padding: '8px 16px' }}
        >
          使用fetch测试
        </button>
        
        <input 
          type="text" 
          value={phone} 
          onChange={(e) => setPhone(e.target.value)} 
          placeholder="输入手机号码" 
          style={{ padding: '8px', width: '150px' }}
        />
        
        <input 
          type="password" 
          value={password} 
          onChange={(e) => setPassword(e.target.value)} 
          placeholder="输入密码" 
          style={{ padding: '8px', width: '150px' }}
        />
      </div>
      
      <div style={{ marginTop: '20px' }}>
        <h3>测试结果:</h3>
        <pre style={{ 
          background: '#f5f5f5', 
          padding: '15px', 
          borderRadius: '5px',
          whiteSpace: 'pre-wrap',
          maxHeight: '400px',
          overflow: 'auto'
        }}>
          {result || '点击按钮开始测试'}
        </pre>
      </div>
    </div>
  );
}
